# 文件的编码-------------------------------------------------------------
# UTF-8、GBK、Big5...等

# 对文件的读取操作-------------------------------------------------------------
# 1.打开
# open(name, mode, encoding),返回一个文件对象
f1 = open("14test.txt", "r")
print(f1)

# 2.操作
# 读取文件
print(f1.read(10))  # 读去十个字节的内容
print(f1.read())    # 下一次读取时，会接着上一次读取的结束位置接着往下读

lines = f1.readlines()  # 读取文件的每一行，并封装到列表中

# for循环读
for line in f1:
    print(line)

# 3.关闭
f1.close()

# 4.with open()，自动关闭
with open("14test.txt", "r", encoding="UTF-8") as f1:
    for line in f1:
        print(line)

# 5.案例
with open("14test.txt", "r", encoding="UTF-8") as f:
    content = f.read()
    print(content.count("test"))

# 对文件的写-------------------------------------------------------------
# 1.打开文件
f2 = open("14write.txt", "w", encoding="UTF-8")
# 2.文件写入
f2.write("test\n")
# 3.内容刷新：即把缓冲区的数据写进磁盘
# f2.flush()
f2.close()  # close()包含flush()

# 追加写入
f3 = open("14write.txt", "a", encoding="UTF-8")
f3.write("追加写")